package com.gitee.andy.rpc.server;

import com.gitee.andy.rpc.entity.RpcRequest;
import com.gitee.andy.rpc.entity.RpcResponse;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class RpcServerHandler extends SimpleChannelInboundHandler<RpcRequest> {

	private final RpcServer rpcServer;

	public RpcServerHandler(RpcServer rpcServer) {
		this.rpcServer = rpcServer;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, RpcRequest msg) throws Exception {
		rpcServer.execute(() -> {
			RpcResponse response = new RpcResponse();
			response.setSeq(msg.getSeq());
			try {
				response.setResult(rpcServer.get(msg.getRpcMethodId()).invoke(msg.getArgs()));
			} catch (Throwable e) {
				response.setError(e);
			}
			ctx.writeAndFlush(response);
		});
	}
}